package com.yitiao.data_algorithms.leetcode.editor.cn;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class FindAllAnagramsInAString {
    // 2022-11-07 18:34:20
    public static void main(String[] args) {
        Solution solution = new FindAllAnagramsInAString().new Solution();
        solution.findAnagrams("dinitrophenylhydrazinetrinitrophenylmethylnitramine", "trinitrophenylmethylnitramine");
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public List<Integer> findAnagrams(String s, String p) {
            List<Integer> res = new ArrayList();
            if (s.length() < p.length()) return res;

            Map<Character, Integer> map = new HashMap<>();
            Map<Character, Integer> window = new HashMap<>();
            for (int i = 0; i < p.length(); i++) {
                map.put(p.charAt(i), map.getOrDefault(p.charAt(i), 0) + 1);
            }

            int left = 0;
            int right = 0;
            while (right < s.length()) {
                window.put(s.charAt(right), window.getOrDefault(s.charAt(right), 0) + 1);
                if (map.equals(window)) {
                    res.add(left);
                }
                right++;
                if ((right - left) + 1 > p.length()) {
                    if (window.get(s.charAt(left)) == 1) {
                        window.remove(s.charAt(left));
                    } else {
                        window.put(s.charAt(left), window.get(s.charAt(left)) - 1);
                    }
                    left++;
                }
            }
            return res;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}